<?php

class Default_Model_SeatMapper {
	
	protected $_dbTable;
	
	public function setDbTable($dbTable)
	{
		if(is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Invalid table data gateway provided');
        }
        $this->_dbTable = $dbTable;
        return $this;
	}
	
	public function getDbTable()
    {
        if (null === $this->_dbTable) {
            $this->setDbTable('Default_Model_DbTable_Seat');
        }
        return $this->_dbTable;
    }
    
	public function save(Default_Model_Seat $seat)
    {
        $data = array(
        	'row'	  => $seat->getRow(),
        	'status'  => $seat->getStatus(),
        	'member'  => $seat->getMember(),
        	'reservationDate'	=> $seat->getReservationDate(),
        );

        if (null === ($id = $seat->getSeatId())) {
            unset($data['seatId']);
            $this->getDbTable()->insert($data);
        } else {
            $this->getDbTable()->update($data, array('seatId = ?' => $id));
        }
    }
    
	public function find($id, Default_Model_Seat $seat)
    {
        $result = $this->getDbTable()->find($id);
        if (0 == count($result)) {
            return;
        }
        $row = $result->current();
        $seat->setSeatId($row->seatId)
                  ->setRow($row->row)
                  ->setStatus($row->status)
                  ->setReservationDate($row->reservationDate);
    }
	
	public function fetchAll()
    {
        $resultSet = $this->getDbTable()->fetchAll();
        $entries   = array();
        foreach ($resultSet as $row) {
            $entry = new Default_Model_Seat();
            $entry->setSeatId($row->seatId)
                  ->setRow($row->row)
                  ->setStatus($row->status)
                  ->setReservationDate($row->reservationDate)
                  ->setMapper($this);
            $entries[] = $entry;
        }
        return $entries;
    }
}

?>